<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminBaseController;
use App\Models\BackendAttachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class Upload extends AdminBaseController
{
    public function index(Request $request)
    {
        if ($request->isMethod('post')) {
            $file = $request->file('file');

            if ($file->isValid()) {
                // 允许上传的文件后缀名
                $allow_extensions = ['mp4', 'jpg', 'gif', 'png'];
                // 获取文件后缀名
                $extension = $file->getClientOriginalExtension();
                if (!in_array($extension, $allow_extensions)) {
                    return $this->fail('文件格式错误');
                } else {
                    $sha1 = hash_file('sha1', $file);
                    $hasFile = $this->checkFile($sha1);
                    if ($hasFile) {
                        return $this->success($hasFile);
                    } else {
                        $fileOriginalName = $file->getClientOriginalName(); // 文件名
                        $fileSize = $file->getSize(); // 文件大小
                        $mimeType = $file->getMimeType(); // 文件类型
                        $realPath = $file->getRealPath(); // 临时存放地址

                        // 文件储存位置及名称
                        $fileName = 'uploads' . '/' . date('Ymd') . '/' . md5(time() . rand(0,1000)) . '.' . $extension;
                        // 保存文件
                        $bool = Storage::disk('public')->put($fileName, file_get_contents($realPath));
                        $url = '';

                        if ($bool) {
                            // 完整url地址
                            $url = url(Storage::url($fileName));
                        }
                        $fileInfo = [
                            'filename' => $fileOriginalName, // 文件原名
                            'filesize' => $fileSize, // 文件大小
                            'mimetype' => $mimeType, // 文件类型
                            'filetype' => $extension, // 拓展名
                            'url' => $url, // 文件保存地址
                            'local_path' => $fileName,
                            'sha1' => $sha1
                        ];
                        $attachment = BackendAttachment::create($fileInfo);
                        return $this->success($attachment);
                    }
                }
            } else {
                return $this->fail('文件上传失败');
            }
        }
    }

    /**
     * 验证文件是否已存在
     */
    protected function checkFile($sha1)
    {
        $file = BackendAttachment::where('sha1', '=', $sha1)->first();
        if ($file) {
            return $file;
        } else {
            return false;
        }
    }

    public function test()
    {
        return $this->success();
    }

}
